package jm.mq.boot_mq.web;

import com.alibaba.fastjson.JSON;
import jm.mq.boot_mq.vo.MsgVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Description 接收消息控制器
 * @date 2022/3/10 10:49
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMessageController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     * @param message 消息
     */
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message){
        log.info("当前时间：{}，发送一条信息给TTL队列：{}",new Date().toString(),message);
        // 执行发送消息到X交换机RoutingKey为XA，XB
        rabbitTemplate.convertAndSend("X","XA","消息来自TTL为10s的队列" + message);
        rabbitTemplate.convertAndSend("X","XB","消息来自TTL为40s的队列" + message);
    }

    /**
     * 发送过期时间和消息
     * @param time 过期时间，单位毫秒
     * @param message 消息
     */
    @GetMapping("/sendTimeAndMsg/{time}/{message}")
    public void sendTimeAndMsg(@PathVariable String time,@PathVariable String message){
        log.info("当前时间：{}，发送一条延迟{}毫秒的信息给TTL队列：{}",new Date().toString(),time,message);
        rabbitTemplate.convertAndSend("X",
                "XC",
                "来自交换机X延迟为" + time +"毫秒的消息：" + message,
                msg -> {
                    //  设置时间
                    msg.getMessageProperties().setExpiration(time);
                    return msg;
                }) ;
    }

    /**
     * 基于插件的延迟队列
     * @param time 延迟时间 , 单位毫秒
     * @param message 消息内容
     */
    @GetMapping("/sendTimeAndMsgByPlugins/{time}/{message}")
    public void sendTimeAndMsgByPlugins(@PathVariable Integer time,@PathVariable String message){
        log.info("当前时间：{}，发送一条延迟{}毫秒的信息给延迟队列：{}",new Date().toString(),time,message);
        rabbitTemplate.convertAndSend("delayed.exchange",
                "delayed.routingKey",message,
                msg -> {
                    msg.getMessageProperties().setDelay(time);
                    return msg;
        });
    }

}
